<script setup lang="ts">
import { onMounted, ref, watch, nextTick } from 'vue'
import { MapComponentProps } from '../MapComponent'
import 'mapbox-gl/dist/mapbox-gl.css'
import { Map } from 'mapbox-gl'
import type { Control } from 'mapbox-gl'
import MapboxMapStore from './utils/MapboxMapStore'
import { MapContainerType } from '../Constant/MapContainerType'

const props = defineProps(MapComponentProps)
const emits = defineEmits(['init'])

const mapContainer = ref()
let map: Map | undefined

// 组件挂载并且可见，初始化地图
onMounted(() => {
    if (props.visible && props.show) {
        initMap()
    }
})

// 组件挂载并且可见，初始化地图
watch([() => props.visible, () => props.show], () => {
    // 地图显示并且没有初始化
    if (props.visible && props.show && !map) {
        initMap()
    } else if (!props.visible) {
        destroyMap()
    }
})

const initMap = () => {
    nextTick(() => {
        _initMap()
    })
}

/**
 * 销毁地图
 */
const destroyMap = () => {
    console.log('销毁地图')
    map && map.remove && map.remove()
    map = undefined
}

const _initMap = () => {
    // 初始化MapBox地图
    map = new Map({
        container: mapContainer.value,
        // style: "mapbox://styles/mapbox/streets-v12",
        // 一定要设置style对象，sources取值为对象，layers取值为数组
        style: {
            version: 8,
            sources: {},
            layers: [],
        },
        center: [115.97852713758685, 30.560407944979296],
        zoom: 3,
        attributionControl: false,
        projection: { name: 'equirectangular' }, // 设置为墨卡托投影
    })
    // @ts-ignore
    window.mapboxMap = map;

    MapboxMapStore.setMap(map)
    // @ts-ignore
    const controls = map?._controls
    controls.forEach((control: Control) => {
            // 去除logo控件, logo控件有次属性
            if ('_updateLogo' in control) {
                map && map.removeControl(control)
            }
        },
    )

    // 移除token校验用于本地化部署
    // @ts-ignore
    map._authenticate = () => {
    }

    emits('init', MapContainerType.MapboxMap)

    map.on('load', () => {
        // 添加谷歌影像图层
        map && map.addLayer({
            id: 'GoogleImageLayer',
            type: 'raster',
            source: {
                'type': 'raster',
                'tiles': ['https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s&x={x}&y={y}&z={z}'],
                'tileSize': 256,
            },
        })
    })
}
</script>

<template>
    <div v-if="visible" v-show="show" ref="mapContainer" class="mapbox-map"></div>
</template>

<style lang="scss" scoped>
@import './css/MapboxMap.scss';
</style>
